#!/usr/bin/env bash

# 将远程分支批量删除
file="delete_branch.txt"

if [ ! -d ".git" ]; then
  echo '不是 git 仓库（或者任何父目录）'
  exit 0
fi

if [ ! -f "$file" ]; then
  git fetch --all
  git remote update origin --prune
  git branch -r > $file
  echo "所有远程分支已保留在 $file 文件中"
  echo "请修改文件, 留下想要删除的分支后, 再次执行此脚本"
  exit 0
fi


# 读取文件内容进行展示
echo '即将删除远程分支: '
while read line
do
  branch_name=${line#origin/}
  if [ -n "$branch_name" ]; then
    echo '   ' $branch_name
  fi
#    git push origin --delete ${line#origin/}
done < $file

# 确认是否删除
read -p 'Y/n: '  confirm
if [ "$confirm" == "Y" ] ||
    [ "$confirm" == "y" ] ||
    [ -z "$confirm" ]; then
  while read line
  do
    branch_name=${line#origin/}
    if [ -n "$branch_name" ]; then
      git push origin --delete $branch_name
    fi
  done < $file
  rm $file
  echo "所有远程分支已删除"
else
  echo "已取消删除"
fi